package com.genius.adminmanager.user.service.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.menu.entity.MenuJson;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.user.service.UserServiceAdapter;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBUtils;
import com.genius.workflow.util.TreeUtils;

@Service("userTreeSelectService")
public class UserTreeSelectServiceImpl extends UserServiceAdapter{

	@Override
	public JSONObject getTreeSelect(JSONObject response) {

		String table = "t_menu";
    	String field = MenuJson.menuId+","+MenuJson.menuId+","+MenuJson.name+","+MenuJson.type;
    	String where = "";
    	String orderBy = " order by "+MenuJson.place;
    	try {
        	JSONArray data = TreeUtils.getTree(MenuJson.menuId, field,MenuJson.parentId, table, MenuJson.state,MenuJson.resource,where, orderBy);
        	
    		JSONArray root = new JSONArray();
    		
    		JSONObject root1 = new JSONObject();
    		JSONArray root1Arr = new JSONArray();
    		root1.put("value", "-1");
    		root1.put("name", "根节点");
    		for(int i = 0;i<data.size();i++){
    			JSONObject datas = data.getJSONObject(i);
    			datas.put("value", datas.getString(MenuJson.menuId));
    			datas.put("name", datas.getString(MenuJson.name));

    			JSONArray children = new JSONArray();
    			for(int index = 0;index<datas.getJSONArray("children").size();index++){
    				JSONObject childrens = changeKey(datas.getJSONArray("children").getJSONObject(index));
    				children.add(childrens);
    			}
    			datas.put("children", children);
    			root1Arr.add(removeKey(datas));
    		}
    		root1.put("children", root1Arr);
    		root.add(root1);
    		
			response.put(ResponseJson.status, ResponseJson.status_Success);
			response.put(ResponseJson.data, root);
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, "查询菜单出错");
		}
		return response;
	}
	private JSONObject changeKey(JSONObject datas){
		if(datas.getString(MenuJson.type).equals("按钮")){
			return null;
		}
		datas.put("value", datas.getString(MenuJson.menuId));
		datas.put("name", datas.getString(MenuJson.name));
		
		if(datas.containsKey("children")){
			JSONArray children = new JSONArray();
			for(int index = 0;index<datas.getJSONArray("children").size();index++){
				JSONObject childrens = changeKey(datas.getJSONArray("children").getJSONObject(index));
				//三级目录 去掉按钮 一级
				if(childrens != null){
					children.add(childrens);
					if(childrens.containsKey("children")){
						if(childrens.getJSONArray("children").size()==0)
							childrens.remove("children");
					}
				}
			}
				datas.put("children", children);
		}
		return removeKey(datas);
	}
	private JSONObject removeKey(JSONObject datas){
		String keys = "value,name,children";
		ArrayList<String> removeKeys = new ArrayList<>();
		for(String key:datas.keySet()){
			if(!keys.contains(key)){
				removeKeys.add(key);
			}
		}
		for(String key:removeKeys){
			datas.remove(key);
		}
		return datas;
	}
	@Override
	public JSONObject getUserByTreeSelect(JSONObject response) {
		Connection conn = null;
		JSONObject groupJson = new JSONObject();
		JSONObject userJson = new JSONObject();
    	try {
    		//打开连接
        	conn = DBUtils.getConnect();
        	String sql = "select groupId,state,name,path,pId from t_group where status = 1";
        	ResultSet rs = DBUtils.query(conn, sql);
        	while(rs.next()){
        		String pId = rs.getString("pId");
        		String groupId = rs.getString("groupId");
        		JSONObject jsonObject = new JSONObject();
        		jsonObject.put("value", groupId);
        		jsonObject.put("state", rs.getString("state"));
        		jsonObject.put("name", rs.getString("name"));
        		jsonObject.put("path", rs.getString("path"));
        		jsonObject.put("pId", pId);
        		JSONArray group = groupJson.getJSONArray(pId);
        		if(group == null){
        			group = new JSONArray();
        		}
        		group.add(jsonObject);
        		groupJson.put(pId, group);
        		pId = null;
        		jsonObject = null;
        		group = null;
        		groupId = null;
        	}
        	rs.close();
        	String userSql = "select userId,name,ifnull(groupId,'')groupId FROM t_user where status = 1";
        	ResultSet userRs = DBUtils.query(conn, userSql);
        	while(userRs.next()){
        		String[] groupId = userRs.getString("groupId").split(",");
        		for (int i = 0; i < groupId.length; i++) {
        			JSONObject jsonObject = new JSONObject();
        			jsonObject.put("value", userRs.getString("userId"));
        			jsonObject.put("name", userRs.getString("name"));
        			jsonObject.put("groupId", groupId[i]);
					JSONArray user = userJson.getJSONArray(groupId[i]);
					if(user == null){
						user = new JSONArray();
					}
					user.add(jsonObject);
					userJson.put(groupId[i], user);
					jsonObject = null;
					user = null;
				}
        		groupId = null;
        		
        	}
        	userRs.close();
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, "查询人员出错");
		} finally {
			DBUtils.closeDBResources(conn);
		}
    	System.out.println(userJson);
    	System.out.println(groupJson);
    	JSONArray tree = groupJson.getJSONArray("-1");
		//插入根目录下的人员及部门
		for (int i = 0; i < tree.size(); i++) {
			JSONObject treeOne = tree.getJSONObject(i);
			//插入子组织
			if(groupJson.getJSONArray(treeOne.getString("value")) != null){
				treeOne.put("children", setTreeChildValue(userJson,groupJson,treeOne.getString("value")));
			}
			//循环插入人员，有自组织与无子组织进行区分
			if(userJson.getJSONArray(treeOne.getString("value")) != null){
				if(treeOne.getJSONArray("children") == null){
					treeOne.put("children", userJson.getJSONArray(treeOne.getString("value")));
				}else{
					treeOne.getJSONArray("children").addAll(userJson.getJSONArray(treeOne.getString("value")));
				}
			}
			tree.set(i, treeOne);
		}
		
		response.put(ResponseJson.status, ResponseJson.status_Success);
		response.put(ResponseJson.data, tree);
		System.out.println(">response<"+response);
		return response;
	}
	@Override
	public JSONObject getUserTreeSelect1(JSONObject response) {
		Connection conn = null;
		JSONObject groupJson = new JSONObject();
		JSONObject userJson = new JSONObject();
    	try {
    		//打开连接
        	conn = DBUtils.getConnect();
        	String sql = "select groupId,state,name,path,pId from t_group where status = 1 and state <4 ";
        	ResultSet rs = DBUtils.query(conn, sql);
        	while(rs.next()){
        		String pId = rs.getString("pId");
        		String groupId = rs.getString("groupId");
        		JSONObject jsonObject = new JSONObject();
        		jsonObject.put("value", groupId);
        		jsonObject.put("state", rs.getString("state"));
        		jsonObject.put("name", rs.getString("name"));
        		jsonObject.put("path", rs.getString("path"));
        		jsonObject.put("pId", pId);
        		JSONArray group = groupJson.getJSONArray(pId);
        		if(group == null){
        			group = new JSONArray();
        		}
        		group.add(jsonObject);
        		groupJson.put(pId, group);
        		pId = null;
        		jsonObject = null;
        		group = null;
        		groupId = null;
        	}
        	rs.close();
        	String userSql = "select userId,name,ifnull(groupId,'')groupId FROM t_user where status = 1";
        	ResultSet userRs = DBUtils.query(conn, userSql);
        	while(userRs.next()){
        		String[] groupId = userRs.getString("groupId").split(",");
        		for (int i = 0; i < groupId.length; i++) {
        			JSONObject jsonObject = new JSONObject();
        			jsonObject.put("value", userRs.getString("userId"));
        			jsonObject.put("name", userRs.getString("name"));
        			jsonObject.put("groupId", groupId[i]);
					JSONArray user = userJson.getJSONArray(groupId[i]);
					if(user == null){
						user = new JSONArray();
					}
					user.add(jsonObject);
					userJson.put(groupId[i], user);
					jsonObject = null;
					user = null;
				}
        		groupId = null;
        		
        	}
        	userRs.close();
		}  catch (ConnectionException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
		} catch (DBClosedException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
		} catch (SQLException e) {
			response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, "查询人员出错");
		} finally {
			DBUtils.closeDBResources(conn);
		}
    	System.out.println(userJson);
    	System.out.println(groupJson);
    	JSONArray tree = groupJson.getJSONArray("-1");
		//插入根目录下的人员及部门
		for (int i = 0; i < tree.size(); i++) {
			JSONObject treeOne = tree.getJSONObject(i);
			//插入子组织
			if(groupJson.getJSONArray(treeOne.getString("value")) != null){
				treeOne.put("children", setTreeChildValue(userJson,groupJson,treeOne.getString("value")));
			}
			//循环插入人员，有自组织与无子组织进行区分
			if(userJson.getJSONArray(treeOne.getString("value")) != null){
				if(treeOne.getJSONArray("children") == null){
					treeOne.put("children", userJson.getJSONArray(treeOne.getString("value")));
				}else{
					treeOne.getJSONArray("children").addAll(userJson.getJSONArray(treeOne.getString("value")));
				}
			}
			tree.set(i, treeOne);
		}
		
		response.put(ResponseJson.status, ResponseJson.status_Success);
		response.put(ResponseJson.data, tree);
		System.out.println(">response<"+response);
		return response;
	}
	//设置树中的值
	private JSONArray setTreeChildValue(JSONObject userJson,JSONObject groupJson,String groupId){
		//获取父组织下的所有子组织
		JSONArray resultArray = groupJson.getJSONArray(groupId);
		//循环插入每个组织的人员
		for (int i = 0; i < resultArray.size(); i++) {
			JSONObject groupOne = resultArray.getJSONObject(i);
			//插入子组织
			if(groupJson.getJSONArray(groupOne.getString("value")) != null){
				groupOne.put("children", setTreeChildValue(userJson,groupJson,groupOne.getString("value")));
			}
			if(userJson.getJSONArray(groupOne.getString("value")) != null){
				if(groupOne.getJSONArray("children") == null){
					groupOne.put("children", userJson.getJSONArray(groupOne.getString("value")));
				}else{
					groupOne.getJSONArray("children").addAll(userJson.getJSONArray(groupOne.getString("value")));
				}
			}
			resultArray.set(i, groupOne);
		}
		return resultArray;
		
	}
}
